<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Skornyakov Anatoliy
 * Date: 01.06.13
 * Time: 14:29
 * 
 */

class UsersController extends Zend_Controller_Action
{
    public function indexAction()
    {
        $mUsers = new Zftest_Model_DbTable_Users();

        $this->view->userList = $mUsers->getList();
    }

    public function addAction()
    {
        $this->view->fUser = new Zftest_Form_User();

        if ($this->getRequest()->isPost()) {
            if ($this->view->fUser->isValid($this->getRequest()->getPost())) {
                $mUsers = new Zftest_Model_DbTable_Users();
                if ($mUsers->add($this->view->fUser->getValues())) {
                    return $this->_redirect($this->view->url(array(), 'usersList'));
                }
            }
        }
    }

    public function editAction()
    {
        $userId = (int)$this->_getParam('userId');

        $this->view->fUser = new Zftest_Form_User();
        $mUsers = new Zftest_Model_DbTable_Users();

        if ($this->getRequest()->isPost()) {
            if ($this->view->fUser->isValid($this->getRequest()->getPost())) {
                if ($mUsers->update($this->view->fUser->getValues(), $userId)) {
                    return $this->_redirect($this->view->url(array(), 'usersList'));
                }
            }
        } else {
            $user = $mUsers->getById($userId);
            $user = $user->toArray();
            $user['phone'] = array();
            if (isset($user['phoneCountry'])) {
                $user['phone']['country'] = $user['phoneCountry'];
                unset($user['phoneCountry']);
            }
            if (isset($user['phoneCity'])) {
                $user['phone']['city'] = $user['phoneCity'];
                unset($user['phoneCity']);
            }
            if (isset($user['phoneNumber'])) {
                $user['phone']['number'] = $user['phoneNumber'];
                unset($user['phoneNumber']);
            }
            if (isset($user['phoneMore'])) {
                $user['phone']['more'] = $user['phoneMore'];
                unset($user['phoneMore']);
            }
            $this->view->fUser->setDefaults($user);
        }
    }
}